<template>
	<el-steps :active="step" finish-status="success" simple style="margin:20px;background-color: aliceblue;">
		<el-step title="服务基本信息" @click="step = 1" />
		<el-step title="字段确定" @click="step = 2" />
		<el-step title="过滤条件" @click="step = 3" />
		<el-step title="信息确认" @click="step = 4" />
	</el-steps>
	<el-form :model="form" label-width="120px" style="width: 80%;" v-if="step == 1">
		<el-form-item label="服务名称">
			<el-input v-model="form.name" />
		</el-form-item>
		<el-form-item label="服务功能描述">
			<el-input v-model="form.desc" type="textarea" />
		</el-form-item>
		<el-form-item label="服务分组">
			<el-select v-model="form.group" placeholder="请选择分组">
				<el-option v-for="(item, index) in groups" :key="index" :label="item.name" :value="item.name" />
			</el-select>
		</el-form-item>
		<el-form-item label="服务所在数据源">
			<el-select v-model="form.datasource" placeholder="请选择数据源">
				<el-option v-for="(item, index) in datasource_list" :key="index" :label="item" :value="item" />
			</el-select>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="step += 1">下一步</el-button>
		</el-form-item>
	</el-form>
	<div v-else-if="step == 2">
		<el-form :model="form" label-width="120px" style="width: 80%;">
			<el-form-item label="返回字段" style="margin-bottom:8px;align-content:center">
				<div v-for="n in param_num" style="display: flex;width: 100%;">
					<el-autocomplete v-model="form.params[n - 1]" :fetch-suggestions="querySearch" clearable
						style="padding-right: 10px;padding-bottom: 10px;width:200px" placeholder="请输入字段关键词" />
					<el-button type="warning" :icon="Minus" size="small" circle plain
						style="position: relative;top: 4px;" @click="onDelete(1, n)" v-if="param_num != 1" />
					<el-button type="success" :icon="Plus" size="small" circle plain
						style="position: relative;top: 4px;" @click="onAdd(1)" v-if="n == param_num" />
				</div>
			</el-form-item>
			<el-form-item label="条件过滤字段">
				<div v-for="n in filter_num" style="display: flex;width: 100%;">
					<el-autocomplete v-model="form.filter[n - 1]" :fetch-suggestions="querySearch" clearable
						style="padding-right: 10px;padding-bottom: 10px;width:200px" placeholder="请输入字段关键词" />
					<el-button type="warning" :icon="Minus" size="small" circle plain
						style="position: relative;top: 4px;" @click="onDelete(2, n)" v-if="filter_num != 1" />
					<el-button type="success" :icon="Plus" size="small" circle plain
						style="position: relative;top: 4px;" @click="onAdd(2)" v-if="n == filter_num" />
				</div>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onSearchSchema">查询服务生成方案</el-button>
			</el-form-item>
		</el-form>
		<div v-if="isSearched">
			<el-table :data="schema" border style="width: 80%;margin:0 20px;">
				<el-table-column label="选择" width="100">
					<template #default="scope">
						<el-radio-group v-model="radio">
							<el-radio :label="scope.$index">{{ '方案' + (scope.$index + 1) }}</el-radio>
						</el-radio-group>
					</template>
				</el-table-column>
				<el-table-column label="方案中各参数来源表">
					<el-table-column v-for="item in Object.keys(raw[0]['label'])" :prop="item" :label="item" />
				</el-table-column>
			</el-table>
			<el-form-item style="margin: 30px 120px;">
				<el-button type="primary" @click="step += 1">下一步</el-button>
				<el-button @click="step -= 1">上一步</el-button>
			</el-form-item>
		</div>

	</div>
	<el-form :model="form" label-width="120px" style="width: 80%;margin-top: 20px;" v-else-if="step == 3">
		<el-form-item v-for="item in form.condition" :label="item['name']">
			<el-select v-model="item['operator']" style="width: 60px;" placeholder=" ">
				<el-option v-for="option in operators[item['type']]" :label="option" :value="option" />
			</el-select>
			<el-switch v-model="item['isVariable']" active-text="动态参数" inactive-text="静态参数" style="margin:0 20px" />
			<el-space wrap v-if="!item['isVariable']" style="width: 50%;">
				<el-input v-model="item['value'][0]" placeholder="请输入参数值" style="width: 30%;" />
				<el-input v-if="item['type'] == 'date'" v-model="item['value']" placeholder="请输入参数值"
					style="width: 30%;" />
				<el-input v-model="item.note" placeholder="请输入参数描述"/>
			</el-space>


		</el-form-item>

		<el-form-item>
			<el-button type="primary" @click="step += 1">下一步</el-button>
			<el-button @click="step -= 1">上一步</el-button>
		</el-form-item>
	</el-form>
	<div v-else>
		<el-descriptions title="服务信息确认" style="margin: 0 20px;" border>
			<el-descriptions-item label="服务名称">{{ form.name }}</el-descriptions-item>
			<el-descriptions-item label="服务功能描述">{{ form.desc }}</el-descriptions-item>
			<el-descriptions-item label="服务分组">{{ form.group }}</el-descriptions-item>
			<el-descriptions-item label="服务所在数据源">{{ form.datasource }}
			</el-descriptions-item>
			<el-descriptions-item label="返回字段">{{ form.params }}
			</el-descriptions-item>
			<el-descriptions-item label="过滤条件">{{ form.condition.map(e => e.name + e.operator + (e.isVariable ? '可变参数' :
					e.value))
			}}
			</el-descriptions-item>
		</el-descriptions>

		<el-form label-width="20px" style="width: 80%;margin-top: 20px;">

			<el-form-item>
				<el-button type="primary" @click="onSubmit">提交</el-button>
				<el-button @click="step -= 1">上一步</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>
  
<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { Plus, Minus } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router';
import { Success } from '../../util/message';
import Api from '../../util/axios'
import { useService } from '../../stores/serviceStore';

let is_create = true
const step = ref(1)
const form = reactive({
	name: '',
	params: [''],
	filter: [''],
	group: '',
	datasource: '',
	desc: '',
	sql: '',
	condition: [
		{ name: '', type: '', operator: '', isVariable: false, value: [], note: '' }
	]
})
const param_num = ref(form.params.length);
const filter_num = ref(form.filter.length);
const router = useRouter()
const route = useRoute()
const groups = reactive<any[]>([])
const param_list = reactive<any[]>([])
const datasource_list = reactive<any[]>([])

onMounted(() => {
	if (route.matched[1].name == 'edit_service') {
		is_create = false
		let service = useService().data
		form.name = service['name']
		form.desc = service['note']
		form.group = service['groupId']
		form.datasource = service['datasourceId']
		param_num.value = service['params'].length
		form.params = service['params'].map(v => v['note'])
	}
	Api.post('/get_group').then((res: any) => {
		groups.push(...res)
	})
	// Api.post('/get_lable').then((res: any) => {
	// 	res.forEach(element => {
	// 		param_list.push({ value: element })
	// 	});
	// })
	Api.post('/show_datasource').then((res: any) => {
		res.forEach(element => {
			datasource_list.push(element.name)
		});
	})
})

watch(() => form.datasource, (newValue) => {
	param_list.length = 0
	Api.post('/get_ds_lable', { "dataSource": newValue }).then((res: any) => {
		res.forEach(element => {
			param_list.push({ value: element })
		});
	})
})

const querySearch = (queryString: string, cb: any) => {
	const createFilter = (queryString: string) => {
		return (item) => {
			return (
				item.value.indexOf(queryString) != -1
			)
		}
	}
	const results = queryString
		? param_list.filter(createFilter(queryString))
		: param_list
	// call callback function to return suggestions
	cb(results)
}
const onAdd = (type) => {
	if (type == 1) {
		param_num.value++
		form.params.push('')
	} else {
		filter_num.value++
		form.filter.push('')
	}

}
const onDelete = (type, index) => {
	if (type == 1) {
		form.params.splice(index - 1, 1)
		param_num.value--
	} else {
		form.filter.splice(index - 1, 1)
		filter_num.value--
	}

}

const isSearched = ref(false)
const schema = reactive<any[]>([])
const raw = reactive<any>([])
const radio = ref(0)
const onSearchSchema = () => {
	Api.post('/newapi1', {
		'selectLabel': form.params, 'conditionLabel': form.filter.filter(e => e)
	}).then((res: any) => {
		raw.length = 0
		raw.push(...res)
		form.condition.length = 0
		schema.length = 0
		res.forEach(e => {
			let data = e['label']
			let temp = {}
			Object.keys(data).forEach(e => temp[e] = data[e]['tables'][0])
			schema.push(temp)
			// TODO
			form.filter.filter(e => e).forEach(e => {
				form.condition.push({ name: e, type: data[e]['type'], operator: operators[data[e]['type']][0], isVariable: false, value: [], note: '' })
			});
		});
		isSearched.value = true
	})
}

const operators = reactive({
	string: ['=', '!='],
	date: ['~']
})

const onSubmit = () => {
	Api.post('/newapi2', {
		"apiName": form.name,
		"apiNote": form.desc,
		"groupName": form.group,
		"dataSourceName": form.datasource,
		"selectLabel": form.params,
		"conditionLabel": form.filter,
		"condition": form.condition,
		"schema": raw[radio.value]
	}).then(res => {
		Success('创建成功')
		router.push({ name: 'service_list' })
	})
}
</script>